package gdepot

import groovy.transform.EqualsAndHashCode
import groovy.transform.ToString

@EqualsAndHashCode(includes='username')
@ToString(includes='username', includeNames=true, includePackage=false)
class User implements Serializable {

	private static final long serialVersionUID = 1

	transient springSecurityService

	String username
	String password
	String fullName
	String gender
	String email
	String phone
	String address
	boolean enabled = true
	boolean accountExpired
	boolean accountLocked
	boolean passwordExpired

	Date createdDate = new Date()
	Date modifiedDate = new Date()

	static hasMany = [roles: UserRole]

	User(String username, String password) {
		this()
		this.username = username
		this.password = password
	}

	Set<Role> getAuthorities() {
		UserRole.findAllByUser(this)*.role
	}

	def beforeInsert() {
		encodePassword()
	}

	def beforeUpdate() {
		if (isDirty('password')) {
			encodePassword()
		}
        modifiedDate = new Date()
	}

	protected void encodePassword() {
		password = springSecurityService?.passwordEncoder ? springSecurityService.encodePassword(password) : password
	}

	static transients = ['springSecurityService']

	static constraints = {
		username blank: false, unique: true
		password blank: false
		email(email:true,unique: true)
		phone(matches: /\d{7,11}/,unique: true)
		address(maxSize: 200,nullable: true, blank: true)
		fullName(nullable: true,blank: true)
		gender(nullable: true,blank: true)
	}

	static mapping = {
		table("login_user")
		password column: '`password`'
	}

	String toString(){
		username
	}
}
